/*
 * @author hope.chen, QQ:77132995, email:kazeik@163.com
 * 2021-03-31 14:26
 * 类说明:
 */
import 'dart:typed_data';

class Hex {
  /// Creates a `Uint8List` by a hex string.
  static Uint8List createUint8ListFromHexString(String hex) {
    if (hex == null) throw new ArgumentError("hex is null");

    var result = new Uint8List(hex.length ~/ 2);
    for (var i = 0; i < hex.length; i += 2) {
      var num = hex.substring(i, i + 2);
      var byte = int.parse(num, radix: 16);
      result[i ~/ 2] = byte;
    }

    return result;
  }

  static String formatBytesAsHexString(Uint8List bytes) {
    if (bytes == null) throw new ArgumentError("The list is null");

    var result = new StringBuffer();
    for (var i = 0; i < bytes.lengthInBytes; i++) {
      var part = bytes[i];
      result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
    }

    return result.toString();
  }
////------------------

  /**
   * Convert byte[] to hex string
   *
   * @param src byte[] data
   * @return hex string
   */
  // String bytesToHexString(List<int> src){
  // List<String> stringBuilder = new List<String>();
  // if (src == null || src.length <= 0) {
  // return null;
  // }
  // for (int i = 0; i < src.length; i++) {
  // int v = src[i] & 0xFF;
  // String hv = Integer.toHexString(v);
  // if (hv.length() < 2) {
  // stringBuilder.append(0);
  // }
  // stringBuilder.append(hv);
  // }
  // return stringBuilder.toString();
  // }
////----------------
  static toHex(Uint8List bArr) {
    int length;
    if (bArr == null || (length = bArr.length) <= 0) {
      return "";
    }
    Uint8List cArr = new Uint8List(length << 1);
    int i = 0;
    for (int i2 = 0; i2 < length; i2++) {
      int i3 = i + 1;
      var cArr2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];

      var index = (bArr[i2] >> 4) & 15;
      cArr[i] = cArr2[index].codeUnitAt(0);
      i = i3 + 1;
      cArr[i3] = cArr2[bArr[i2] & 15].codeUnitAt(0);
    }
    return new String.fromCharCodes(cArr);
  }

  static toUnitList(String str) {
    int length = str.length;
    if (length % 2 != 0) {
      str = "0" + str;
      length++;
    }
    List<int> s = str.toUpperCase().codeUnits;
    Uint8List bArr = Uint8List(length >> 1);
    for (int i = 0; i < length; i += 2) {
      bArr[i >> 1] = ((hex(s[i]) << 4) | hex(s[i + 1]));
    }
    return bArr;
  }

  static hex(int c) {
    if (c >= '0'.codeUnitAt(0) && c <= '9'.codeUnitAt(0)) {
      return c - '0'.codeUnitAt(0);
    }
    if (c >= 'A'.codeUnitAt(0) && c <= 'F'.codeUnitAt(0)) {
      return (c - 'A'.codeUnitAt(0)) + 10;
    }
  }
}
